#include <stdio.h>
#include <stdlib.h>
#include <android/looper.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <unistd.h>

int sockcallback(int fd, int events, void* data){
	printf("fd=%d, events=%d\n", fd, events);
	return 0;
}

int main(void) {
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0){
		perror("create socket failed");
		exit(-1);
	}
	struct sockaddr_in server_addr;
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(9318);
	server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	if (connect(sockfd, (struct sockaddr*)&server_addr,
				sizeof(server_addr)) == -1){
		perror("connect socket failed");
		exit(-1);
	}
	char* input = "Hello World";
	int send_num = send(sockfd, input, strlen(input), 0);
	if (send_num == -1){
		perror("send failed");
		exit(-1);
	}

	ALooper * looper = ALooper_prepare(0);
	if (ALooper_addFd(looper, sockfd,
					  sockfd, ALOOPER_EVENT_INPUT,
					  sockcallback, NULL) == -1){
		perror("addFd failed");
		exit(-1);
	}
	int outFd, outEvents, result;
	if ((result = ALooper_pollOnce(2000, &outFd, &outEvents, NULL)) >= 0){
		printf("outFd: %d, outEvents: %d\n", outFd, outEvents);
	}else{
		printf("result: %d\n", result);
	}
	close(sockfd);
}
